<template>
  <div class="weightItemList">
    <van-nav-bar
      :title="$route.meta.title"
      left-arrow
      :border="false"
      @click-left="clickLeft"
      @click-right="clickRight"
      class="nav-bar"
    >
      <template #right>
        <van-icon name="success" size="20" /><span
          style="color: #fff; font-size: 20px"
          >保存</span
        >
      </template>
    </van-nav-bar>
    <div class="item-style">
      <div style="display: flex; justify-content: space-between">
        <van-tag plain type="primary" style="margin: 20px 10px 10px 10px"
          >信息检索</van-tag
        >
      </div>
      <van-row gutter="20" type="flex" justify="left" align="center">
        <van-col
          span="4"
          style="
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
          "
          @click="openScan('material')"
        >
          <van-icon name="scan" /><span>物料类型：</span>
        </van-col>
        <van-col span="8">
          <van-dropdown-menu>
            <van-dropdown-item
              v-model="materialType"
              :options="materialTypeArr"
            />
          </van-dropdown-menu>
        </van-col>
        <van-col span="4" style="text-align: center">
          <span>物料名称：</span>
        </van-col>
        <van-col span="8">
          <van-dropdown-menu>
            <van-dropdown-item
              v-model="materialCode"
              :options="materialNameArr"
              @change="MaterialName"
            />
          </van-dropdown-menu>
        </van-col>
      </van-row>
      <van-row gutter="20" type="flex" justify="left" align="center">
        <van-col span="4" style="text-align: center">
          <span>批号：</span>
        </van-col>
        <van-col span="8">
          <van-dropdown-menu>
            <van-dropdown-item v-model="batch" :options="batchArr" />
          </van-dropdown-menu>
          <!-- <van-field
            readonly
            clickable
            :value="batch"
            placeholder="请选择"
            @click="showBatch = true"
          /> -->
        </van-col>
        <van-col span="4" style="text-align: center">
          <span>检验编号：</span>
        </van-col>
        <van-col span="8">
          <van-dropdown-menu>
            <van-dropdown-item v-model="testID" :options="testArr" />
          </van-dropdown-menu>
        </van-col>
      </van-row>
      <van-row gutter="20" type="flex" justify="left" align="center">
        <van-col span="4" style="text-align: center">
          <span>标准：</span>
        </van-col>
        <van-col span="8">
          <van-dropdown-menu>
            <van-dropdown-item
              v-model="standardCode"
              :options="standardArr"
              @change="StandardName"
            />
          </van-dropdown-menu>
        </van-col>
        <van-col span="4" style="text-align: center">
          <span>检验记录：</span>
        </van-col>
        <van-col span="8" class="recordStyle">
          <van-field
            readonly
            clickable
            v-model="recordName"
            placeholder="请选择"
            @click="showPicker = true"
            class="select-record"
          />
        </van-col>
      </van-row>
      <van-row gutter="20" type="flex" justify="left" align="center">
        <van-col span="12" class="deviceItemStyle" style="padding-right: 10px">
          <van-field
            v-model="deviceItemCode"
            name="deviceItemCode"
            label="称重项目:"
            readonly
            placeholder="请选择称重项目"
          >
            <template #input>
              <mult-select
                :dataList="deviceItemArr"
                @chooseValue="updataDeviceItemCode"
              />
            </template>
          </van-field>
        </van-col>
        <van-col span="4" style="text-align: center"> </van-col>
        <van-col span="8"> </van-col>
      </van-row>
      <div style="display: flex; justify-content: space-between">
        <div>
          <van-tag plain type="primary" style="margin: 20px 10px 10px 10px"
            >主要内容</van-tag
          >
          <span>({{ itemNum }})</span>
        </div>

        <van-button
          size="small"
          type="info"
          style="
            float: right;
            margin-right: 26px;
            margin-top: 10px;
            padding: 0px 20px;
            height: 0.65rem;
          "
          @click="addWeight()"
          >新增</van-button
        >
      </div>
      <div class="checkItem" v-if="showItem">
        <van-list :finished="finished" finished-text="暂无数据">
          <van-swipe-cell
            v-for="(v, i) in WeightItemModels"
            :key="i"
            ref="swipecell"
          >
            <van-cell
              title-class="custom-title"
              value-class="custom-value"
              label-class="custom-label"
              :title="v.materialName"
            >
              <template #label>
                <div>编号：{{ v.taskItemNo }}</div>
                <div>批号：{{ v.batch }}</div>
                <div>标准：{{ v.standardName }}</div>
                <div>检验记录：{{ v.recordName }}</div>
                <div>项目名称：{{ v.deviceItemName }}</div>
              </template>
            </van-cell>
            <template #right>
              <van-button
                square
                block
                type="danger"
                style="height: 100%"
                text="删除"
                @click.stop="delInfo(i)"
              />
            </template>
          </van-swipe-cell>
        </van-list>
      </div>
    </div>
    <div class="scan" v-if="scanShow">
      <div id="bcid">
        <div style="height: 40%"></div>
        <p class="tip">...载入中...</p>
      </div>
      <footer>
        <button @click="closeModel">退出</button>
      </footer>
    </div>
    <van-popup v-model="showPicker" position="bottom" :lock-scroll="false">
      <van-cascader
        v-model="recordValue"
        :options="recordArr"
        @close="showPicker = false"
        @finish="onFinish"
      />
    </van-popup>
    <van-popup v-model="showBatch" position="bottom">
      <van-picker
        show-toolbar
        :columns="batchArr"
        @cancel="showBatch = false"
        @confirm="onConfirm"
      />
    </van-popup>
  </div>
</template>

<script>
import {
  NavBar,
  Cell,
  CellGroup,
  Notify,
  Col,
  Row,
  DropdownMenu,
  DropdownItem,
  Icon,
  Tag,
  Button,
  Popup,
  Field,
  Picker,
  List,
  SwipeCell,
  Dialog,
} from "vant";
import {
  getDictionarySelect,
  getMaterialSelect,
  getTestStandardSelect,
  GetFlatRecordReportActiveTree,
  getBatchIdsTwo,
  getReportId,
  getRecordWeightAttributes,
  getTestByTestId,
  saveTaskItems,
} from "@/api/base";
import { to } from "@/utils";
import MultSelect from "./components/MultSelect";
import DeviceName from "./components/DeviceName";

let scan = null;
export default {
  name: "weightItemList",
  components: {
    [NavBar.name]: NavBar,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Notify.name]: Notify,
    [Col.name]: Col,
    [Row.name]: Row,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Icon.name]: Icon,
    [Tag.name]: Tag,
    [Button.name]: Button,
    DeviceName,
    MultSelect,
    [Popup.name]: Popup,
    [Field.name]: Field,
    [Picker.name]: Picker,
    [List.name]: List,
    [SwipeCell.name]: SwipeCell,
    [Dialog.name]: Dialog,
  },
  data() {
    return {
      finished: false,
      token: "",
      materialType: "",
      materialCode: "",
      materialName: "",
      weight: "",
      unity: "",
      value2: "a",
      materialTypeArr: [],
      materialNameArr: [],
      scanShow: false,
      deviceName: "",
      deviceItemCode: "",
      deviceItemName: "",
      deviceItemArr: [],
      standardCode: "",
      standardName: "",
      standardArr: [],
      weighMode: "",
      weighName: "",
      weighModeArr: [
        { value: "1", text: "称重模式" },
        { value: "10", text: "皮重、毛重、净重模式" },
        { value: "15", text: "皮重、净重、毛重模式" },
        { value: "20", text: "减重模式" },
        { value: "40", text: "干燥失重模式" },
      ],
      standardValue: "",
      showPicker: false, //检验记录
      recordName: "",
      recordCode: "",
      recordArr: [],
      recordValue: "",
      showBatch: false,
      batch: "",
      batchArr: [],
      testID: "",
      testArr: [],
      ws: "",
      socket: "",
      socketUrl: "",
      gDomain: "",
      scanType: "",
      scanObj: {},
      timer: null,
      WeightItemModels: [],
      taskItemNo: 1,
      showItem: true,
      deviceArr: [],
      itemNum: 0,
    };
  },
  watch: {
    materialType(val) {
      if (val) {
        this.getMaterialName(this.materialType);
      }
    },
    materialCode(val) {
      this.deviceItemCode = "";
      this.deviceItemArr = [];
      if (val) {
        this.getStandardList(val);
        this.getBatchIds(val);
      }
    },
    batch(val) {
      if (val) {
        this.getReportId(val);
      }
    },
    testID(val) {
      this.getRecordWeight();
      if (val) {
        this.testArr.map((item) => {
          if (val == item.testID) {
            this.standardCode = item.standardCode;
            this.standardArr.map((item1) => {
              if (item1.id == item.standardCode) {
                this.standardName = item1.text;
              }
            });
          }
        });
      }
    },
    recordCode() {
      this.getRecordWeight();
    },
    standardCode() {
      this.getRecordList();
      this.getRecordWeight();
    },
  },
  mounted() {
    this.gDomain = localStorage.getItem("domainKey");
    this.token = localStorage.getItem("tokenKey");
    this.getMaterialType();
  },
  methods: {
    clickLeft() {
      if (scan && scan != "") {
        scan.close();
      }
      this.$router.replace({ name: "home" });
    },
    async getMaterialType() {
      var that = this;
      var queryParams = {
        pageModel: { Search: ["MaterielType"], Token: this.token },
      };
      const [err, res] = await to(getDictionarySelect(queryParams));
      if (err) return;
      // this.materialType = res.Result[0].value;
      this.materialTypeArr = Array.isArray(res.Result) ? res.Result : [];
    },
    async getMaterialName(type) {
      var that = this;
      var queryParams = {
        pageModel: { Search: [type], Token: this.token },
      };
      const [err, res] = await to(getMaterialSelect(queryParams));
      if (err) return;
      if (this.scanObj) {
        this.materialCode = this.scanObj.materialCode;
      } else {
        this.materialCode = res.Result[0].value;
      }
      this.materialNameArr = Array.isArray(res.Result) ? res.Result : [];
    },
    async getStandardList(code) {
      var that = this;
      var queryParams = {
        queryModel: { code: code, Token: this.token },
      };
      const [err, res] = await to(getTestStandardSelect(queryParams));
      if (err) return;
      var dataArr = res.Result;
      dataArr.map((item) => {
        item.value = item.id;
      });
      if (this.scanObj) {
        this.standardCode = this.scanObj.testStandard;
        this.standardName = this.scanObj.standardBaseOn;
      } else {
        this.standardCode = res.Result[0].value;
        this.standardName = res.Result[0].text;
      }
      this.standardArr = res.Result;
    },
    async getRecordList() {
      var that = this;
      var queryParams = {
        materialCode: this.materialCode,
        StandardCode: this.standardCode,
        TestID: this.testID,
        Token: this.token,
      };
      const [err, res] = await to(GetFlatRecordReportActiveTree(queryParams));
      if (err) return;
      var result = res.Result;
      if (!result || result.length == 0) return false;
      this.dowhile(result);
      this.recordArr = result;
      this.recordName = "";
      this.recordCode = "";
    },
    async getBatchIds(code) {
      var that = this;
      this.batchArr = [];
      this.batch = "";
      this.testID = "";
      var queryParams = {
        materialCode: code,
        order: "desc",
        origin: "02",
        search: "",
        Token: this.token,
      };
      const [err, res] = await to(getBatchIdsTwo(queryParams));
      if (err) return;
      if (res.Result.batchs && res.Result.batchs.length > 0) {
        res.Result.batchs.map((item) => {
          var obj = {
            value: item,
            text: item,
          };
          this.batchArr.push(obj);
        });
      }
      if (this.scanObj) {
        this.batch = this.scanObj.batchID;
      }
    },
    async getReportId(id) {
      var that = this;
      var queryParams = {
        pageModel: {
          Search: [this.materialCode, id],
          Token: this.token,
        },
      };
      const [err, res] = await to(getReportId(queryParams));
      if (err) return;
      var dataArr = res.Result;
      if (dataArr.length > 0) {
        dataArr.map((item) => {
          item.text = item.testID;
          item.value = item.testID;
        });
      }
      if (this.scanObj) {
        this.testID = this.scanObj.testID;
      } else {
        this.testID = dataArr[0].value;
      }

      this.testArr = dataArr;
    },
    async getRecordWeight() {
      var that = this;
      var queryParams = {
        MaterialCode: this.materialCode,
        recordCode: this.recordCode,
        TestID: this.testID,
        BatchID: this.batch,
        standardCode: this.standardCode,
        Token: this.token,
      };
      const [err, res] = await to(getRecordWeightAttributes(queryParams));
      if (err) return;
      var dataArr = res.Result.weightings;
      if (dataArr.length > 0) {
        dataArr.map((item) => {
          item.text = item.attributeName;
          item.value = item.attributeCode;
        });
      }
      this.deviceItemArr = dataArr;
    },
    clickRight() {
      if (this.WeightItemModels && this.WeightItemModels.length > 0) {
        var params = {
          Token: this.token,
          WeightItemModels: this.WeightItemModels,
        };
        saveTaskItems(params)
          .then((response) => {
            if (response.ErrorCode == 0) {
              Notify({ type: "success", message: response.ErrorMsg });
              this.taskItemNo = 1;
              this.WeightItemModels = [];
              this.itemNum = 0;
              this.getRecordWeight();
              this.scanObj = {};
            } else {
              Notify({ type: "danger", message: response.ErrorMsg });
            }
          })
          .catch(() => {});
      } else {
        Notify({ type: "danger", message: "请添加数据" });
      }
    },
    dowhile(b) {
      for (var i = 0; i < b.length; i++) {
        b[i].text = b[i].name;
        b[i].value = b[i].code;
        if (b[i].children && b[i].children.length > 0) {
          this.dowhile(b[i].children);
        } else {
          delete b[i].children;
        }
      }
    },
    openScan(type) {
      var that = this;
      this.scanType = type;
      this.scanShow = true;
      this.timer = setTimeout(that.startRecognize, 500);
    },
    startRecognize() {
      var that = this;
      this.timer = null;
      if (!window.plus) return;
      scan = new plus.barcode.Barcode("bcid");
      scan.onmarked = onmarked;
      scan.start();
      function onmarked(type, result, file) {
        switch (type) {
          case plus.barcode.QR:
            type = "QR";
            break;
          case plus.barcode.EAN13:
            type = "EAN13";
            break;
          case plus.barcode.EAN8:
            type = "EAN8";
            break;
          default:
            type = "其它" + type;
            break;
        }
        that.scanShow = false;
        if (that.scanType == "device") {
          var str = decodeURIComponent(result);
          var strObj = JSON.parse(str);
          that.deviceName = strObj.equipmentName;
          that.instCode = strObj.equipmentCode;
        } else if (that.scanType == "material") {
          //或去物料类型
          that.getScanType(JSON.parse(result).testID);
        }
        scan.close();
      }
    },
    closeModel() {
      this.scanShow = false;
      if (!window.plus) return;
      scan.close();
    },
    async getScanType(id) {
      var params = {
        queryModel: {
          Code: id,
          Token: this.token,
        },
      };
      const [err, res] = await to(getTestByTestId(params));
      this.scanObj = res.Result;
      // this.materialCode = "";
      if (this.materialType && this.materialType == res.Result.materialType) {
        if (this.materialCode == res.Result.materialCode) {
          this.getBatchIds(this.materialCode);
        } else {
          this.materialCode = res.Result.materialCode;
        }
      } else {
        this.materialType = res.Result.materialType;
      }
    },
    onFinish({ selectedOptions }) {
      this.showPicker = false;
      var len = selectedOptions.length;
      var toDetail = selectedOptions[len - 1];
      this.recordName = toDetail.text;
      this.recordCode = toDetail.value;
    },
    onConfirm(value) {
      this.batch = value;
      this.showBatch = false;
    },
    MaterialName(val) {
      this.materialNameArr.map((item) => {
        if (item.value == val) {
          this.materialName = item.text;
        }
      });
    },
    StandardName(val) {
      this.standardArr.map((item) => {
        if (item.value == val) {
          this.standardName = item.text;
        }
      });
    },
    WeighName(val) {
      this.weighModeArr.map((item) => {
        if (item.value == val) {
          this.weighName = item.text;
        }
      });
    },
    // DeviceItemName(val) {
    //   this.deviceItemArr.map((item) => {
    //     if (item.value == val) {
    //       this.deviceItemName = item.text;
    //       this.deviceItemCode = item.value;
    //     }
    //   });
    // },
    addWeight() {
      var _that = this;
      if (this.testID == "") {
        Notify({ type: "danger", message: "检验单号不能为空！" });
        return false;
      }
      if (this.recordCode == "") {
        Notify({ type: "danger", message: "记录编码不能为空！" });
        return false;
      }
      // if (this.attributeCode == "") {
      //   Notify({ type: "danger", message: "项目编码不能为空！" });
      //   return false;
      // }
      if (this.deviceArr == 0) {
        Notify({ type: "danger", message: "请选择称重项目！" });
        return false;
      }
      _that.addWeightInfo();
    },
    addWeightInfo() {
      var _that = this;
      var WeightItemModels2 = _that.WeightItemModels;
      var newArr = [..._that.deviceArr];
      var newArr1 = [...newArr.values()];
      if (WeightItemModels2.length > 0) {
      }
      newArr1.map((item) => {
        var isSame = false;
        WeightItemModels2.map((item1) => {
          if (item1.attributeCode == item.attributeCode) {
            isSame = true;
          }
        });
        if (!isSame) {
          var obj = {
            taskItemNo: this.taskItemNo++,
            testID: this.testID,
            recordCode: this.recordCode,
            attributeCode: item.value,
            // weighMode: this.weighMode,
            recordName: this.recordName,
            materialName: this.materialName,
            batch: this.batch,
            standardName: this.standardName,
            weighName: this.weighName,
            deviceItemName: item.text,
          };
          WeightItemModels2.push(obj);
        }
      });
      var newMap = new Map();
      for (let item of WeightItemModels2) {
        newMap.set(item.attributeCode, item);
      }
      var newArr2 = [...newMap.values()];
      var sortArr = newArr2.sort(_that.compare("sort"));
      _that.WeightItemModels = sortArr;
      _that.itemNum = _that.WeightItemModels.length;
    },
    compare(prop) {
      return function (obj1, obj2) {
        var val1 = Number(obj1[prop]);
        var val2 = Number(obj2[prop]);
        if (val1 < val2) {
          return -1;
        } else if (val1 > val2) {
          return 1;
        } else {
          return 0;
        }
      };
    },
    delInfo: function (num) {
      var _that = this;
      Dialog.confirm({
        message: "确定删除吗？",
      })
        .then(() => {
          for (var i = 0; i < _that.WeightItemModels.length; i++) {
            if (i == num) {
              _that.WeightItemModels.splice(i, 1);
              break;
            }
          }
        })
        .catch(() => {});
    },
    updataDeviceItemCode: function (code) {
      this.deviceArr = code;
    },
  },
};
</script>
<style>
.van-nav-bar__title {
  color: #fff;
}
/* .van-icon-arrow-left {
  color: #fff !important;
} */
.van-cell__title {
  text-align: left;
  font-weight: 500;
}
.van-dropdown-menu__bar {
  box-shadow: 0 0 0;
  height: 36px;
}
.item-style .van-row .van-col .van-field__control {
  text-align: center;
}
.item-style .van-row{
  margin: 0 5px;
}
</style>
<style scoped lang="less">
.weightItemList {
  height: 100%;
  overflow-y: hidden;
  margin: 0;
  padding: 0;
}

.nav-bar {
  background-color: #49bbef;
}
.item-style {
  font-size: 0.34rem;
  height: calc(100% - 40px);
  overflow-y: auto;
}
.item-style .van-row {
  height: 36px;
  //   line-height: 40px;
}
.scan {
  height: 100%;
  width: 100%;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;

  #bcid {
    width: 100%;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 1rem;
    text-align: center;
    color: #fff;
    background: #ccc;
    font-size: 20px;
    z-index: 999;
    .closeModel {
      position: absolute;
      top: 20px;
      right: 20px;
    }
  }
  footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    bottom: 0;
    height: 1rem;
    font-size: 20px;
    button {
      height: 100%;
      width: 100%;
      border: none;
    }
  }
}

/deep/.van-dropdown-menu__title {
  width: 100%;
  height: 0.69rem;
  border: 1px solid #ddd;
  font-size: 0.34rem;
  text-align: center;
}
/deep/.van-dropdown-menu__title::after {
  display: none;
}
/deep/.van-dropdown-item__content {
  height: 80%;
}
.spaStyle /deep/ .van-cell {
  padding: 0 16px;
}
.recordStyle > div {
  padding: 0 !important;
}
.recordStyle /deep/ .van-cell {
  padding: 0 16px;
}
/deep/.van-dropdown-item__option {
  padding: 5px 15px;
}
.deviceItemStyle > div {
  padding: 0;
}
// .deviceItemStyle /deep/.van-field__body {
//   // width: 95% !important;
//   // margin-left: 0.95rem;
// }
.deviceItemStyle /deep/.van-cell__title {
  text-align: center;
  width: 31.5%;
  color: #000;
}
.deviceItemStyle /deep/.van-popup .van-cell__title {
  text-align: left;
}
/deep/.van-dropdown-item {
  // top: 3rem!important;
  margin-top: 1px;
}
</style>